package com.gaoch.simweather.tools;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;



import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;




/**
 * Created by GaoCh on 2018/7/23.
 */

public class Utility {
    private static final String THEME_WHITE="white";
    private static final String THEME_BLACK="black";
    private static final String THEME_AUTO="auto";
    private static final String THEME_NOT="not";
    private static String themeMode=THEME_NOT;




    /**
     * 按照最大范围来放大图片
     * @param path
     * @return
     */
    public static Drawable ReSizePic(String path,int maxHeight,int maxWidth,Context context){
        BitmapDrawable bd=(BitmapDrawable)Drawable.createFromPath(path);
        Bitmap bkg1=bd.getBitmap();
        float prePicWidth=bkg1.getWidth();
        float prePicHeight=bkg1.getHeight();
        double displayScale=(maxWidth+0.0)/maxHeight;
        double prePicScale=prePicWidth/prePicHeight;
        Log.e("GGG","显示区域:"+maxHeight+","+maxWidth);
        Log.e("GGG","图片尺寸:"+prePicHeight+","+prePicWidth);
        Log.e("GGG","显示区域比例:"+displayScale);
        Log.e("GGG","图片比例:"+prePicScale);
        if(prePicScale>displayScale){
            //图片宽度过大,将宽度放大到maxWidth
            float scaleFactor=maxWidth/prePicWidth;
            //按照高度缩放
            Log.e("GGG","缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            return new BitmapDrawable(context.getResources(),bkg_scaled);


        }else{
            //背景图片长度过大，将长度放大到maxHeight
            float scaleFactor=maxHeight/prePicHeight;
            //按照宽度缩放
            Log.e("GGG","缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            return new BitmapDrawable(context.getResources(),bkg_scaled);
        }
    }
    /**
     * 按照最大范围来放大图片
     * @param bitmap
     * @return
     */
    public static Drawable ReSizePic(Bitmap bitmap,int maxHeight,int maxWidth,Context context){
        Bitmap bkg1=bitmap;
        float prePicWidth=bkg1.getWidth();
        float prePicHeight=bkg1.getHeight();
        double displayScale=(maxWidth+0.0)/maxHeight;
        double prePicScale=prePicWidth/prePicHeight;
        Log.e("GGG","显示区域:"+maxHeight+","+maxWidth);
        Log.e("GGG","图片尺寸:"+prePicHeight+","+prePicWidth);
        Log.e("GGG","显示区域比例:"+displayScale);
        Log.e("GGG","图片比例:"+prePicScale);
        if(prePicScale>displayScale){
            //图片宽度过大,将宽度放大到maxWidth
            float scaleFactor=maxWidth/prePicWidth;
            //按照高度缩放
            Log.e("GGG","缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            return new BitmapDrawable(context.getResources(),bkg_scaled);


        }else{
            //背景图片长度过大，将长度放大到maxHeight
            float scaleFactor=maxHeight/prePicHeight;
            //按照宽度缩放
            Log.e("GGG","缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            return new BitmapDrawable(context.getResources(),bkg_scaled);
        }
    }




    /**
     * 按照尺寸剪裁图片
     * @param path
     * @return
     */
    public static Drawable getCuteedBkg(String path, Context context, float width,float height){
        BitmapDrawable bd=(BitmapDrawable)Drawable.createFromPath(path);
        Bitmap bkg1=bd.getBitmap();
        //Log.d(ConstValue.appName,"屏幕尺寸:"+width+","+height);

        float prePicWidth=bkg1.getWidth();
        float prePicHeight=bkg1.getHeight();
        //Log.d(ConstValue.appName,"原始图片尺寸:"+prePicWidth+","+prePicHeight);
        float displayScale=width/height;
        float prePicScale=prePicWidth/prePicHeight;
        //Log.d(ConstValue.appName,"屏幕宽高比例:"+displayScale+",原始图片宽高比例:"+prePicScale);
        if(displayScale<prePicScale){

            //背景图片宽度过大,按照高度缩放
            float scaleFactor=height/prePicHeight;
            //按照高度缩放
           // Log.d(ConstValue.appName,"缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            float pic_width=bkg_scaled.getWidth();
            float pic_height=bkg_scaled.getHeight();
            Bitmap bkg_nedded=Bitmap.createBitmap(bkg_scaled,(((int)pic_width-(int)width)/2),0,(int)width,(int)height);
          //  Log.d(ConstValue.appName,"剪裁后的图片:"+bkg_nedded.getWidth()+","+bkg_nedded.getHeight());
            return new BitmapDrawable(context.getResources(),bkg_nedded);


        }else{
            //背景图片宽度过小
            float scaleFactor=width/prePicWidth;
            //按照宽度缩放
           // Log.d(ConstValue.appName,"缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            float pic_width=bkg_scaled.getWidth();
            float pic_height=bkg_scaled.getHeight();
            Bitmap bkg_nedded=Bitmap.createBitmap(bkg_scaled,0,((int)pic_height-(int)height)/2,(int)width,(int)height);
           // Log.d(ConstValue.appName,"剪裁后的图片:"+bkg_nedded.getWidth()+","+bkg_nedded.getHeight());
            return new BitmapDrawable(context.getResources(),bkg_nedded);
        }
    }


    /**
     * 按照屏幕尺寸剪裁图片
     * @param drawable
     * @return
     */
    public static Drawable getCuteedBkg(Drawable drawable, Context context, WindowManager windowManager){
        BitmapDrawable bd1=(BitmapDrawable)drawable;
        Bitmap bkg1=bd1.getBitmap();

        DisplayMetrics metrics =new DisplayMetrics();
        windowManager.getDefaultDisplay().getRealMetrics(metrics);

        float width = metrics.widthPixels;
        float height = metrics.heightPixels;
       // Log.d(ConstValue.appName,"屏幕尺寸:"+width+","+height);

        float prePicWidth=bkg1.getWidth();
        float prePicHeight=bkg1.getHeight();
     //   Log.d(ConstValue.appName,"原始图片尺寸:"+prePicWidth+","+prePicHeight);
        float displayScale=width/height;
        float prePicScale=prePicWidth/prePicHeight;
     //   Log.d(ConstValue.appName,"屏幕宽高比例:"+displayScale+",原始图片宽高比例:"+prePicScale);
        if(displayScale<prePicScale){

            //背景图片宽度过大,按照高度缩放
            float scaleFactor=height/prePicHeight;
            //按照高度缩放
        //    Log.d(ConstValue.appName,"缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            float pic_width=bkg_scaled.getWidth();
            float pic_height=bkg_scaled.getHeight();
            Bitmap bkg_nedded=Bitmap.createBitmap(bkg_scaled,(((int)pic_width-(int)width)/2),0,(int)width,(int)height);
          //  Log.d(ConstValue.appName,"剪裁后的图片:"+bkg_nedded.getWidth()+","+bkg_nedded.getHeight());
            return new BitmapDrawable(context.getResources(),bkg_nedded);


        }else{
            //背景图片宽度过小
            float scaleFactor=width/prePicWidth;
            //按照宽度缩放
       //     Log.d(ConstValue.appName,"缩放后的图片:"+(int)(prePicWidth*scaleFactor)+","+(int)(prePicHeight*scaleFactor));
            Bitmap bkg_scaled= Bitmap.createScaledBitmap(bkg1,(int)(prePicWidth*scaleFactor),(int)(prePicHeight*scaleFactor), true);
            float pic_width=bkg_scaled.getWidth();
            float pic_height=bkg_scaled.getHeight();
            Bitmap bkg_nedded=Bitmap.createBitmap(bkg_scaled,0,((int)pic_height-(int)height)/2,(int)width,(int)height);
          //  Log.d(ConstValue.appName,"剪裁后的图片:"+bkg_nedded.getWidth()+","+bkg_nedded.getHeight());
            return new BitmapDrawable(context.getResources(),bkg_nedded);
        }
    }

    /**
     * 在Android10上无法使用
     * @param path
     * @return
     */
    public static Bitmap LoadLocalBitmap(String path){
        BitmapDrawable bd=(BitmapDrawable)Drawable.createFromPath(path);
       return bd.getBitmap();
    }


    /**
     * 如果Activity的布局设置android:fitsSystemWindows="true"，则无效
     * @param mAc
     */
    public static void setFullScreen_origin(Activity mAc){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = mAc.getWindow();
            mAc.requestWindowFeature(Window.FEATURE_NO_TITLE);
            if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.P){
                //在P下允许全屏app使用刘海屏
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                window.setAttributes(lp);
            }
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }
    public static void setStatusBarColor(Activity mAc, boolean needDarkStatusBar,int color){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = mAc.getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if(needDarkStatusBar){
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |  View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }else{
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |  View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(color);
        }
    }

    public static boolean setStatusBarTextColor(Activity activity, boolean lightStatusBar) {
        // 设置状态栏字体颜色 白色与深色
        Window window =activity.getWindow();
        View decor = window.getDecorView();
        int ui = decor.getSystemUiVisibility();
        ui |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (lightStatusBar) {
                ui |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                ui &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
        }
        decor.setSystemUiVisibility(ui);
        return true;
    }







    //判断字符串是否为整数
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }


    /**
     * 获取状态栏的高度
     * @param context
     * @return
     */

    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId =context.getResources().getIdentifier("status_bar_height","dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
    /**
     * 获取导航栏高度
     * @param context
     * @return 导航栏高度
     * @version 1.0
     */
    public static int getNavigationHeight(Context context) {
        int result = 0;
        int resourceId=0;
        int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid!=0){
            resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
            return context.getResources().getDimensionPixelSize(resourceId);
        }else
            return 0;
    }

    public static String getFileName(String url){
        String s[]=url.split("/");
        if(s.length<=1){
            s=url.split("\\\\");
        }
        return s[s.length-1];

    }


    /**
     * 从本地选择媒体文件，转化为路径
     * @param uri
     * @param context
     * @return
     */
    public static String getPathFromUri(Uri uri,Context context){
        if (Build.VERSION.SDK_INT >= 29){
            String s=uri.getPath();
           // Log.d(ConstValue.appName,s);
        }
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];
        Uri contentUri = null;
        if ("image".equals(type)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
            contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
            contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        final String selection = "_id=?";
        final String[] selectionArgs = new String[]{split[1]};
        return getDataColumn(context, contentUri, selection, selectionArgs);
    }

    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }




    /**
     * 将Bitmap写入SD卡中的一个文件中,并返回写入文件的Uri
     * @param bm
     * @param dirPath
     * @return
     */
    public static Uri saveBitmap(Bitmap bm, String dirPath) {
        //新建文件夹用于存放裁剪后的图片
        File tmpDir = new File(dirPath);
        if (!tmpDir.exists()){
            tmpDir.mkdir();
        }

        //新建文件存储裁剪后的图片
        File img = new File(tmpDir.getAbsolutePath() + "/avator.png");
        try {
            //打开文件输出流
            FileOutputStream fos = new FileOutputStream(img);
            //将bitmap压缩后写入输出流(参数依次为图片格式、图片质量和输出流)
            bm.compress(Bitmap.CompressFormat.PNG, 95, fos);
            //刷新输出流
            fos.flush();
            //关闭输出流
            fos.close();
            //返回File类型的Uri
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 时间戳转日期，精确到分钟
     * @param timeMilles
     * @return
     */
    public static String timeMilles2str(long timeMilles){
        if(timeMilles==0){
          //  Log.e(ConstValue.appName,"转换时间失败：传递进来的毫秒为0");
            return "";
        }
        Date time = new Date();
        Date time_now = new Date();
        time.setTime(timeMilles);
        time_now.setTime(System.currentTimeMillis());
        SimpleDateFormat formatter;
        if(time.getYear()==time_now.getYear()&&time.getMonth()==time_now.getMonth()&&time.getDay()==time_now.getDay()){
            formatter = new SimpleDateFormat("HH:mm");
        }else if(time.getYear()==time_now.getYear()&&time.getMonth()==time_now.getMonth()){
            formatter = new SimpleDateFormat("dd日 HH:mm");
        }else if(time.getYear()==time_now.getYear()){
            formatter = new SimpleDateFormat("MM月 dd日 HH:mm");
        }else{
            formatter = new SimpleDateFormat("yyyy年 MM月 dd日 HH:mm");
        }
        return formatter.format(time);
    }

    /**
     * 时间戳转日期，精确到日,格式：yyyy:MM:dd
     * @param timeMilles
     * @return
     */
    public static String timeMilles2strWithDay(long timeMilles){
        if(timeMilles==0){
         //   Log.e(ConstValue.appName,"转换时间失败：传递进来的毫秒为0");
            return "";
        }
        Date time = new Date();
        time.setTime(timeMilles);
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(time);
    }


    /**
     * 时间戳转日期，精确到日,格式：MM:dd
     * @param timeMilles
     * @return
     */
    public static String timeMilles2strMMDD(long timeMilles){
        if(timeMilles==0){
        //    Log.e(ConstValue.appName,"转换时间失败：传递进来的毫秒为0");
            return "";
        }
        Date time = new Date();
        time.setTime(timeMilles);
        SimpleDateFormat formatter=new SimpleDateFormat("MM月dd日");
        return formatter.format(time);
    }


    /**
     * 时间戳转日期，精确到日
     * @param timeMilles
     * @return
     */
    public static String timeMilles2strRecent(long timeMilles){
        if(timeMilles==0){
            //Log.e(ConstValue.appName,"转换时间失败：传递进来的毫秒为0");
            return "-";
        }
        Date time = new Date();
        Date time_now = new Date();
        time.setTime(timeMilles);
        time_now.setTime(System.currentTimeMillis());
        SimpleDateFormat formatter;
        if(timeMillesInSameDay(System.currentTimeMillis(),timeMilles)){
            formatter = new SimpleDateFormat("HH:mm");
        }else if(time.getYear()==time_now.getYear()&&time.getMonth()==time_now.getMonth()){
            formatter = new SimpleDateFormat("dd号");
        }else if(time.getYear()==time_now.getYear()){
            formatter = new SimpleDateFormat("MM/dd");
        }else{
            formatter = new SimpleDateFormat("yy/MM/dd");
        }
        return formatter.format(time);
    }



    /**
     * 判断两个时间戳是否为同一天
     * @param t1
     * @return true为在同一天
     * @version 1.0
     */
    public static boolean timeMillesInSameDay(long t1,long t2){
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yy:MM:dd");
        String str1=formatter.format(t1);
        String str2=formatter.format(t2);
        return str1.equals(str2);
    }



}
